import os
import time
import random
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
import shutil
from flask import Flask, request, jsonify
from sklearn.decomposition import PCA
from sklearn.preprocessing import LabelEncoder
from config import OUTPUT_PCA_PATH  # 确保配置路径正确

app = Flask(__name__)

# **字体设置**
if os.name == "nt":  # Windows
    print("正在使用 Windows 环境...")
    plt.rcParams["font.family"] = "SimHei"  # Windows 默认使用黑体
elif os.name == "posix":  # Linux
    print("正在使用 Linux 环境...")
    font_path = "/usr/share/fonts/wqy-zenhei/wqy-zenhei.ttc"

    if os.path.exists(font_path):
        my_font = fm.FontProperties(fname=font_path)
        plt.rcParams["font.family"] = my_font.get_name()
    else:
        print(" [警告] 未找到 wqy-zenhei，使用 DejaVu Sans 作为备用字体！")
        plt.rcParams["font.family"] = "DejaVu Sans"

# **确保负号正常显示**
plt.rcParams['axes.unicode_minus'] = False

# **清除 Matplotlib 缓存，防止字体问题**
matplotlib_cache = os.path.expanduser("~/.cache/matplotlib")
if os.path.exists(matplotlib_cache):
    shutil.rmtree(matplotlib_cache)
    print(" Matplotlib 字体缓存已清除，确保字体设置生效。")

def perform_pca(csv_file, target_column=None, n_components=2):
    df = pd.read_excel(csv_file)

    # 处理数据
    if target_column:
        X = df.drop(columns=[target_column]).values  # 特征
        y = df[target_column].values  # 标签
        label_encoder = LabelEncoder()
        y_encoded = label_encoder.fit_transform(y)
        target_names = label_encoder.classes_
    else:
        X = df.values
        y_encoded = None
        target_names = None

    # 进行 PCA 降维
    pca = PCA(n_components=n_components)
    X_pca = pca.fit_transform(X)

    # 解释方差比例
    explained_variance = pca.explained_variance_ratio_.tolist()
    cumulative_variance = sum(explained_variance)

    # 生成文件名（时间戳 + 随机数）
    os.makedirs(OUTPUT_PCA_PATH, exist_ok=True)
    timestamp = int(time.time() * 1000)
    random_number = random.randint(1000, 9999)
    output_file_name = f"{timestamp}_{random_number}.png"
    output_file_path = os.path.join(OUTPUT_PCA_PATH, output_file_name)

    # 绘制 PCA 结果
    plt.figure(figsize=(8, 6))
    if y_encoded is not None:
        for i, target_name in enumerate(target_names):
            plt.scatter(
                X_pca[y_encoded == i, 0], X_pca[y_encoded == i, 1],
                label=target_name, alpha=0.8, s=50
            )
    else:
        plt.scatter(X_pca[:, 0], X_pca[:, 1], alpha=0.8, s=50)

    plt.xlabel("第一主成分")
    plt.ylabel("第二主成分")
    plt.title("抗压强度 PCA 结果")
    if y_encoded is not None:
        plt.legend(loc="best")
    plt.grid()
    plt.savefig(output_file_path)
    plt.close()  # 关闭 plt 避免内存泄漏

    print(f"散点图已保存为: {output_file_path}")
    print("PCA 第一主成分数据:", X_pca[:, 0].tolist())
    print("PCA 第二主成分数据:", X_pca[:, 1].tolist())

    return output_file_path, explained_variance, cumulative_variance, X_pca[:, 0].tolist(), X_pca[:, 1].tolist()
